
#include "PCH.h"
#include "ObjReader.h"

CVector ObjReader::ParseVertex(const char * buffer) {

		std::istringstream stream(buffer);

		CVector v;
		stream >> v.x >> v.y >> v.z;
//		v.z=-v.z;
		
		v.x *=100.0f;
		v.y *=100.0f;
		v.z *=100.0f;
		v.z -=600.0f;
		return v;
	}

CTriangleObject ObjReader::ParseTri(const char * buffer, const std::vector<CVector> & vertices) {

		std::istringstream stream(buffer);

		int a, b, c, d;
		stream >> a;
		//stream.ignore(2);
		stream >> b;
		//stream.ignore(2);
		stream >> c;
		//stream.ignore(2);
		stream >> d;

		
		CMaterial Glass;
		Glass.color = CColor(0.6f,0.7f,1.0f);
		Glass.diffuse = 0.1f;
		Glass.specular = 0.90f;
		Glass.reflection = CColor(0.6f,0.7f,1.0f);
		Glass.transparency = 0.7f;
		Glass.refractionIndex = CColor(1/0.55,1/0.55,1/0.55);
		Glass.specularExponent = 200;

		
		CTriangleObject T;
		T.Material=Glass;
		
		T.Point1 = vertices[a-1];
		T.Point2 = vertices[b-1];
		T.Point3 = vertices[c-1];
		

		return T;
	}

void ObjReader::Parse(std::istream & stream, std::vector<CTriangleObject*> & Tris) {

	std::vector<CVector> vertices;

	while(!stream.eof()) {

		char buffer[1024];
		stream.getline(&buffer[0], sizeof(buffer));

		switch(buffer[0]) {
			case 'v' : {
				vertices.push_back(ParseVertex(buffer + 2));
				break;
					   }
			case 'f' : {

				CTriangleObject* T = new CTriangleObject;
				*T = ParseTri(buffer + 2, vertices);
				Tris.push_back(T);
				break;
					   }
			case 'B' : { return; }
		}
	}
}



void ObjReader::LoadFile(std::string &FileName,std::vector<CRenderableObject*> &Objects)
{
	std::ifstream file("caro.obj");

	std::vector<CTriangleObject*> TriMesh;
	Parse(file, TriMesh);
	for(std::vector<CTriangleObject*>::iterator it=TriMesh.begin();it!=TriMesh.end();++it)
	{
		Objects.push_back(*it);
	}

};

